/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Frontera;

import Entidad.Solicitud;
import control.ControlCliente;
import control.ControlSolicitud;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Juan
 */
public class FRegistroSolicitud extends javax.swing.JFrame {
       
    public FRegistroSolicitud() {
        initComponents();
        this.setLocationRelativeTo(null);
        inicializar();
    }
    
    private void inicializarAnalisis(){
        this.modelosAnalisis = new java.util.ArrayList<>();
        this.modelosAnalisis.add((ModeloTablaAnalisis)TAnalisis.getModel());
    }
    
    private void cargarNumeroSolicitud() {
        try {
            numeroSolicitud = controlSolicitud.siguienteNumeroSolicitud();
            LNumeroSolicitud.setText(String.format("SA%04d", numeroSolicitud));
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(),
                    "Error SQL", javax.swing.JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public void cargarClientes(){
        CBClientes.setEnabled(false);
        CBClientes.setModel(new DefaultComboBoxModel(new Object[]{"<Cargando lista de clientes>"}));
        TrabajadorCargarClientes cargarClientes =
                new TrabajadorCargarClientes(controlCliente){
            @Override
            protected void done(){
                try {
                    nombresClientes = get();
                    if (nombresClientes != null) {
                        CBClientes.setModel(new DefaultComboBoxModel(nombresClientes));
                        CBClientes.setSelectedIndex(0);
                        CBClientes.setEnabled(true);
                    } else {
                        CBClientes.setModel(new DefaultComboBoxModel(new Object[] {"No hay clientes registrados."}));
                    }
                } catch (InterruptedException | ExecutionException e){
                    JOptionPane.showMessageDialog(FRegistroSolicitud.this, e.getMessage(),
                    "Error en hilo trabajador", javax.swing.JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        
        cargarClientes.execute();
    }
    
    private void inicializar(){
        cargarNumeroSolicitud();
        inicializarAnalisis();
        cargarClientes();
        
        ajustarTablaAnalisis();
        TAnalisis.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        tca = new TableColumnAdjuster(TMuestras);
        TMuestras.getColumn("Identificación").setPreferredWidth(100);
        TMuestras.getColumn("Cantidad (gramos)").setPreferredWidth(150);
        TMuestras.getColumn("Observaciones").setPreferredWidth(200);
        
        TMuestras.setValueAt(null, 0, 0);
        TMuestras.setValueAt(0.0, 0, 1);
        TMuestras.setValueAt(null, 0, 2);
        TMuestras.setValueAt(false, 0, 3);
        TMuestras.setValueAt(false, 0, 4);
        
        TMuestras.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                tablaMuestrasSeleccionCambiada();
            }            
        });
        
        CBAplicarTodas.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CBAplicarTodasSeleccionado();
            }
        });
    }
    
    private void ajustarTablaAnalisis() {
        TAnalisis.getColumn("Rush").setPreferredWidth(50);
        TAnalisis.getColumn("Normal").setPreferredWidth(60);
        TAnalisis.getColumn("Análisis").setPreferredWidth(400);
    }
    
    private void tablaMuestrasSeleccionCambiada(){
        int filaAnterior = muestraActual;
        int filaSeleccionada = TMuestras.getSelectedRow();
        if(filaSeleccionada != -1){
            if(TMuestras.getRowCount() > 1)BEliminarMuestra.setEnabled(true);
            if(!CBAplicarTodas.isSelected()){
                modelosAnalisis.set(filaAnterior, (ModeloTablaAnalisis)TAnalisis.getModel());
                TAnalisis.setModel((ModeloTablaAnalisis) modelosAnalisis.get(filaSeleccionada));
                ajustarTablaAnalisis();
                muestraActual = filaSeleccionada;
                LMuestraActual.setText((String)TMuestras.getValueAt(filaSeleccionada, 0));
            }
        }else{
            BEliminarMuestra.setEnabled(false);
        }
    }
    
    private void CBAplicarTodasSeleccionado(){
        if(CBAplicarTodas.isSelected()){
            LAnalisisMuestra.setText("Análisis para todas las Muestras:");
            LMuestraActual.setText(null);
            modelosAnalisis.set(muestraActual,(ModeloTablaAnalisis)TAnalisis.getModel());
            TAnalisis.setModel(new ModeloTablaAnalisis());
        }else{
            LAnalisisMuestra.setText("Análisis para la Muestra:");
            int seleccionActual = TMuestras.getSelectedRow();
            muestraActual = seleccionActual;
            TAnalisis.setModel((ModeloTablaAnalisis)modelosAnalisis.get(seleccionActual));
            LMuestraActual.setText((String)TMuestras.getValueAt(seleccionActual, 0));
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PRegistroSolicitud = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        LNumeroSolicitud = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        CBClientes = new javax.swing.JComboBox();
        BRegistrar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        TFOrigen = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        TFRegistroEnvio = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        BAceptar = new javax.swing.JButton();
        BCancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TMuestras = new javax.swing.JTable();
        CBControlCobros = new javax.swing.JComboBox();
        CBOrdenServicio = new javax.swing.JComboBox();
        BAdicionarMuestra = new javax.swing.JButton();
        BEliminarMuestra = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        TAnalisis = new javax.swing.JTable(){
            @Override
            public boolean isCellEditable(int rowIndex, int colIndex) {
                if(colIndex == 0)
                if(rowIndex >=11)
                return false;
                return true;
            }

            @Override
            public void setValueAt(Object aValue, int row, int col) {
                if(col <= 1 && (boolean) aValue){
                    int other = 1;
                    if(col == 1) other = 0;
                    super.setValueAt(aValue, row, col);
                    super.setValueAt(false, row, other);
                }else{
                    super.setValueAt(aValue, row, col);
                }        
            }
        };
        LAnalisisMuestra = new javax.swing.JLabel();
        CBAplicarTodas = new javax.swing.JCheckBox();
        LMuestraActual = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        TFResponsable = new javax.swing.JTextField();
        TFControlCobros = new javax.swing.JTextField();
        TFOrdenServicio = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        CBDisposicion = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registro de Solicitud número "+LNumeroSolicitud.getText());
        setMinimumSize(getPreferredSize());

        PRegistroSolicitud.setBorder(javax.swing.BorderFactory.createTitledBorder("Registro de Solicitud"));

        jLabel1.setText("Número de Solicitud:");

        LNumeroSolicitud.setText("NDS");

        jLabel2.setText("Cliente:");

        CBClientes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Cargando lista de clientes>" }));
        CBClientes.setEnabled(false);

        BRegistrar.setText("Registrar Nuevo Cliente");
        BRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRegistrarActionPerformed(evt);
            }
        });

        jLabel3.setText("Lugar de Origen:");

        jLabel4.setText("Registro de Envío:");

        jLabel5.setText("Control de Cobros:");

        jLabel6.setText("Orden de Servicio:");

        BAceptar.setText("Aceptar");
        BAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAceptarActionPerformed(evt);
            }
        });

        BCancelar.setText("Cancelar");
        BCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCancelarActionPerformed(evt);
            }
        });

        TMuestras.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        TMuestras.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"", null, "", null, null}
            },
            new String [] {
                "Identificación", "Cantidad (gramos)", "Observaciones", "Radioactiva", "Magnética"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        TMuestras.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        TMuestras.setEditingColumn(0);
        TMuestras.setEditingRow(0);
        TMuestras.setNextFocusableComponent(BAceptar);
        TMuestras.setValueAt(false, 0, 3);
        TMuestras.setValueAt(false, 0, 4);
        TMuestras.getSelectionModel().setSelectionInterval(0, 0);
        jScrollPane1.setViewportView(TMuestras);

        CBControlCobros.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Facturar", "Factura #" }));
        CBControlCobros.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(CBControlCobros.getSelectedIndex() == 0)
                TFControlCobros.setEnabled(false);
                else
                TFControlCobros.setEnabled(true);
            }
        });

        CBOrdenServicio.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No aplica", "Pendiente", "Orden de Compra #", "Orden de Servicio #" }));
        CBOrdenServicio.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(CBOrdenServicio.getSelectedIndex() <= 1)
                TFOrdenServicio.setEnabled(false);
                else
                TFOrdenServicio.setEnabled(true);
            }
        });

        BAdicionarMuestra.setText("Adicionar Muestra");
        BAdicionarMuestra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAdicionarMuestraActionPerformed(evt);
            }
        });

        BEliminarMuestra.setText("Eliminar Muestra");
        BEliminarMuestra.setEnabled(false);
        BEliminarMuestra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BEliminarMuestraActionPerformed(evt);
            }
        });

        TAnalisis.setModel(new ModeloTablaAnalisis());
        TAnalisis.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane2.setViewportView(TAnalisis);

        LAnalisisMuestra.setText("Análisis para todas las Muestras:");

        CBAplicarTodas.setSelected(true);
        CBAplicarTodas.setText("Aplicar a todas las Muestras");

        jLabel8.setText("Registro de Muestras:");

        jLabel7.setText("Responsable:");

        TFControlCobros.setEnabled(false);

        TFOrdenServicio.setEnabled(false);

        jLabel9.setText("Disposición de Muestras:");

        CBDisposicion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Entregar", "Disponer" }));

        javax.swing.GroupLayout PRegistroSolicitudLayout = new javax.swing.GroupLayout(PRegistroSolicitud);
        PRegistroSolicitud.setLayout(PRegistroSolicitudLayout);
        PRegistroSolicitudLayout.setHorizontalGroup(
            PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(CBDisposicion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                .addComponent(CBOrdenServicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(TFControlCobros, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(TFOrdenServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel7)
                            .addComponent(jLabel1))
                        .addGap(30, 30, 30)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(TFResponsable)
                                    .addComponent(TFRegistroEnvio)
                                    .addComponent(TFOrigen)
                                    .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                        .addComponent(CBControlCobros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addComponent(CBClientes, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(BRegistrar)
                                .addGap(170, 170, 170))
                            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                .addComponent(LNumeroSolicitud)
                                .addContainerGap())))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PRegistroSolicitudLayout.createSequentialGroup()
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                .addComponent(BAceptar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(BCancelar))
                            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                .addComponent(BAdicionarMuestra)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(BEliminarMuestra))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                                .addComponent(LAnalisisMuestra)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(LMuestraActual, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(CBAplicarTodas)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        PRegistroSolicitudLayout.setVerticalGroup(
            PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(LNumeroSolicitud, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(CBClientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(BRegistrar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(PRegistroSolicitudLayout.createSequentialGroup()
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(TFOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(TFRegistroEnvio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(TFResponsable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(CBControlCobros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(TFControlCobros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(CBOrdenServicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(TFOrdenServicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel9)
                            .addComponent(CBDisposicion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(LAnalisisMuestra)))
                    .addComponent(LMuestraActual, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BAdicionarMuestra)
                    .addComponent(BEliminarMuestra)
                    .addComponent(CBAplicarTodas))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(PRegistroSolicitudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BAceptar)
                    .addComponent(BCancelar))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PRegistroSolicitud, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PRegistroSolicitud, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
        
    private void BAdicionarMuestraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAdicionarMuestraActionPerformed
        DefaultTableModel model = (DefaultTableModel) this.TMuestras.getModel();
        model.addRow(new Object[]{"",0.0,"",false,false});
        TMuestras.setModel(model);
        this.modelosAnalisis.add(new ModeloTablaAnalisis());
        int numeroFilasMuestras = TMuestras.getRowCount();
        if(numeroFilasMuestras > 1) BEliminarMuestra.setEnabled(true);
        tca.adjustColumns();
        TMuestras.getSelectionModel().setSelectionInterval(numeroFilasMuestras-1, numeroFilasMuestras-1);
    }//GEN-LAST:event_BAdicionarMuestraActionPerformed

    private void BEliminarMuestraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BEliminarMuestraActionPerformed
        DefaultTableModel model = (DefaultTableModel) this.TMuestras.getModel();
        int filaSeleccionada = TMuestras.getSelectedRow();
        model.removeRow(filaSeleccionada);
        TMuestras.setModel(model);
        modelosAnalisis.remove(filaSeleccionada);
        if(filaSeleccionada == 0){
            TAnalisis.setModel((ModeloTablaAnalisis)modelosAnalisis.get(0));
            TMuestras.getSelectionModel().setSelectionInterval(0, 0);
        }else{
            muestraActual--;
            TAnalisis.setModel((ModeloTablaAnalisis)modelosAnalisis.get(muestraActual));
            TMuestras.getSelectionModel().setSelectionInterval(filaSeleccionada-1, filaSeleccionada-1);
        }
    }//GEN-LAST:event_BEliminarMuestraActionPerformed


    private void BAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAceptarActionPerformed
       
       ProgressMonitor monitor = new ProgressMonitor(this, "Registrando la Solicitud", "", 0, 100);
       
       java.util.Date fechaActual = new java.util.Date();
       java.sql.Date SQLFechaActual = new java.sql.Date(fechaActual.getTime()); 
       java.sql.Time SQLHoraActual = new java.sql.Time(fechaActual.getTime());
       
       Solicitud nuevaSolicitud = new Solicitud();
       int IDCliente;
       
       try{
           if (!CBClientes.isEnabled()) throw new Exception("No hay ningún cliente seleccionado.");
           IDCliente = controlCliente.buscarIDCliente((String)CBClientes.getSelectedItem());
           nuevaSolicitud.setIdCliente(IDCliente);
           nuevaSolicitud.setFechaRadicacion(SQLFechaActual);
           nuevaSolicitud.setHoraRadicacion(SQLHoraActual);
           nuevaSolicitud.setLugarOrigen(TFOrigen.getText().trim());
           nuevaSolicitud.setRegistroEnvio(TFRegistroEnvio.getText().trim());
           nuevaSolicitud.setQuienRecibe(TFResponsable.getText().trim());
           nuevaSolicitud.setControlCobros(CBControlCobros.getSelectedItem().toString()+TFControlCobros.getText().trim());
           nuevaSolicitud.setOrdenServicio(CBOrdenServicio.getSelectedItem().toString()+TFOrdenServicio.getText().trim());
       }catch (Exception e){
           JOptionPane.showMessageDialog(this, e.getMessage(),
                    "Error de base de datos.", javax.swing.JOptionPane.ERROR_MESSAGE);
           return;
       }
       
       if (CBAplicarTodas.isSelected()) {
           modelosAnalisis.set(0, (ModeloTablaAnalisis) TAnalisis.getModel());
       }
       
       TrabajadorRegistrarSolicitud trabajador = 
               new TrabajadorRegistrarSolicitud(modelosAnalisis,
                                                CBAplicarTodas.isSelected(),
                                                IDCliente,
                                                numeroSolicitud,
                                                CBDisposicion.getSelectedIndex(),
                                                (DefaultTableModel) TMuestras.getModel(),
                                                monitor, 
                                                nuevaSolicitud)
               {
                   
                   @Override
                   protected void done() {
                       try {
                           get();
                           
                           /* //muestra mensaje de registro exitoso 
                           JOptionPane.showMessageDialog(FRegistroSolicitud.this, "La solicitud fue registrada con éxito",
                                   "Creación exitosa", JOptionPane.INFORMATION_MESSAGE);*/
                           
             //pregunta si se desean o no imprimir los codigos de dicha solicitud
                          // 0=imprimir, 1= no imprimir.
                          int seleccion = JOptionPane.showOptionDialog(
                                FRegistroSolicitud.this,
                                "Su solicitud ha sido registrada correctamente, "
                                   + "desea imprimir los codigos de barra de las muestras"
                                   + "de dicha solicitud ?", 
                                "Solicitud ingresada",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE,
                                null,    // null para icono por defecto.
                                new Object[] { "Imprimir", "No Imprimir"},   // null para YES, NO y CANCEL
                                "Imprimir");
                          
              //--------------------------------------------------------------------            
                           FRegistroSolicitud.this.dispose();
                       } catch (InterruptedException | ExecutionException e) {
                           JOptionPane.showMessageDialog(FRegistroSolicitud.this, e.getMessage(),
                                   "Error de registro", JOptionPane.ERROR_MESSAGE);
                       }    
                   }
               };
       
       trabajador.execute();
    
    }//GEN-LAST:event_BAceptarActionPerformed

    private void BRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRegistrarActionPerformed
        registro = new FRegistroClientes();
        registro.setPadre(this);
        this.setEnabled(false);
        registro.setVisible(true);
    }//GEN-LAST:event_BRegistrarActionPerformed

    private void BCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_BCancelarActionPerformed


    /**
     * @param args the command line arguments
     */
    
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException |
                 InstantiationException |
                 IllegalAccessException |
                 UnsupportedLookAndFeelException ignore) {}
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FRegistroSolicitud().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAceptar;
    private javax.swing.JButton BAdicionarMuestra;
    private javax.swing.JButton BCancelar;
    private javax.swing.JButton BEliminarMuestra;
    private javax.swing.JButton BRegistrar;
    private javax.swing.JCheckBox CBAplicarTodas;
    private javax.swing.JComboBox CBClientes;
    private javax.swing.JComboBox CBControlCobros;
    private javax.swing.JComboBox CBDisposicion;
    private javax.swing.JComboBox CBOrdenServicio;
    private javax.swing.JLabel LAnalisisMuestra;
    private javax.swing.JLabel LMuestraActual;
    private javax.swing.JLabel LNumeroSolicitud;
    private javax.swing.JPanel PRegistroSolicitud;
    private javax.swing.JTable TAnalisis;
    private javax.swing.JTextField TFControlCobros;
    private javax.swing.JTextField TFOrdenServicio;
    private javax.swing.JTextField TFOrigen;
    private javax.swing.JTextField TFRegistroEnvio;
    private javax.swing.JTextField TFResponsable;
    private javax.swing.JTable TMuestras;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
    private String[] nombresClientes;
    private FRegistroClientes registro;
    private ArrayList<ModeloTablaAnalisis> modelosAnalisis;
    private int muestraActual = 0;
    private ControlCliente controlCliente = new ControlCliente();
    private ControlSolicitud controlSolicitud = new ControlSolicitud();
    private int numeroSolicitud;
    private TableColumnAdjuster tca;
}
